#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#include <string>
using namespace std;

void Usage(const string &proc)
{
    cout << "\n\tUsage: " << proc << " 服务器ip 服务器port" << endl
         << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    // 创建套接字
    if (socketfd < 0)
    {
        cerr << "socket error" << endl;
        return 1;
    }
    // 无需显示bind

    // 客户端中建立与服务器的连接
    string server_ip = argv[1];
    uint16_t server_port = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &(server.sin_addr));

    int n = connect(socketfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "connect error" << endl;
        return 2;
    }

    // 给服务器发消息
    string message;
    while (true)
    {
        cout << "Please Enter: ";
        getline(cin, message);
        write(socketfd, message.c_str(), message.size());

        char inbuffer[4096];
        int n = read(socketfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
    }

    close(socketfd);

    return 0;
}